<?php
$creater = DataTemplatePHPFileCreater::GetInstance();

class DataTemplatePHPFileCreater
{
	private $header;
	private $keyword;
	private static $_instance;

	private function __construct()
	{
		$keyword = config( 'DATA_TEMPLATE_FIRST_WORD' );
		if ( isset ( $keyword ) ) {
			$keyword = 'DT';
		} 
	}
	
	public static function GetInstance()    
	{    
	    if(! (self::$_instance instanceof self) )
	    {
	        self::$_instance = new self();
	    }
	    return self::$_instance;    
	  
	}   
	
	public function createTemplatePHPFile( $file_path = null )
	{
		if ( getCSVHeader( $file_path ) ) {
			debug_log("$file_path is not exist!");
			return false;
		}
		
		$file_name = dirname( $file_path );
		$php_context = getTemplatePHPContext( $file_name );
		
		if ( file_put_contents( LIB_DATATPL_PATH . $file_name . '.class.php', $php_context ) ) {
			debug_log( "file_put_contents $filename failed!" );
			return false;
		}
		
	}
	
	private function getTemplatePHPContext( $file_path )
	{
		$keyword = config( 'DATA_TEMPLATE_FIRST_WORD' );
		if ( isset ( $keyword ) ) {
			$keyword = 'DT';
		}
		
		$class_name = $keyword . basename($file_path, ".csv");
		$bass_class_name = "DataTemplate";
		
		ob_start();		
		echo <<<EOD
<?php
class $class_name extends $bass_class_name
\{
	public static $s_szFileName = '$file_name';
EOD;
	foreach ( $this->header as $header ) {
		echo <<<EOD
	
	function Get{$header}()
	\{
		return \$this->data['$header'];
	\}
EOD;
	}

	echo <<<EOD
\}
?>
EOD;
		$context = ob_get_contents();
		ob_end_clean();
		
		return $context;
	}
	
	private function getCSVHeader( $file_path = null )
	{
		$fp = fopen( $file_path, "rt" );
        if ( ! $fp ) {
            return false;
        }
        
    	$array_header = array();
       	if ( ! feof( $fp ) ) {
            $this->header = fgetcsv( $fp );	// 从文件指针中读入一行并解析 CSV 字段
		}
		
        fclose( $fp );
		
		return $array_header;
	}
	
	
}

?>